var rp = require('request-promise');
var cheerio = require('cheerio');

var options ={
    uri:'http://aqicn.org/city/xian/',
    headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
    },
    transform: function (body) {
        return cheerio.load(body);
    }
}

var domoticz_url ="http://192.168.100.150:8080";
var aqi_idx =21;
var temp_idx=22;
var pm10_idx=23;
var pm25_idx=24;

exports.aqi_job =function(){
    rp(options)
    .then(function($){
        //console.log($.html());
        var aqi_value = $("#aqiwgtvalue").text();
        var pm25_value = $("#cur_pm25").text();
        var pm10_value = $("#cur_pm10").text();
        var temp = $("#cur_t .temp").text();
        var humidity = $("#cur_h").text();
        //console.log(pm25_value);
        //console.log(pm10_value);
        //console.log(aqi_value);
        //console.log(temp+"°C");

        var obj={
            'temp':temp,
            'humidity':humidity,
            'pm25':pm25_value,
            'pm10':pm10_value,
            'aqi':aqi_value
        }
        return obj;
    })
    .then(function(obj){
        
        var aqi_url = domoticz_url+"/json.htm?type=command&param=udevice&idx="+aqi_idx+"&nvalue="+obj['aqi']+"&svalue="+obj['aqi'];
        rp(aqi_url).then();
        var temp_humidity = obj["temp"]+";"+obj["humidity"]+";0";
        var temp_url =domoticz_url+"/json.htm?type=command&param=udevice&idx="+temp_idx+"&nvalue=0&svalue="+temp_humidity;
      console.log(temp_url);
        rp(temp_url).then();
        var pm10_url =domoticz_url+"/json.htm?type=command&param=udevice&idx="+pm10_idx+"&nvalue="+obj["pm10"]+"&svalue="+obj['pm10'];
        rp(pm10_url).then();
        var pm25_url =domoticz_url+"/json.htm?type=command&param=udevice&idx="+pm25_idx+"&nvalue="+obj['pm25']+"&svalue="+obj['pm25'];
        rp(pm25_url).then();
    })
    .catch(function(err){
        console.log("访问异常");
        console.log(err);
    })
  }
